package FileReading;

import GameOfLife.*;

import java.awt.List;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class LIFFileReader {

	public ArrayList<Cell> listOfCells = new ArrayList<Cell>();
	public int[] valuesOfLife = { 2, 3 }; // tableau des valeurs de survie de
											// base
	public int[] valuesOfDeath = { 3 }; // tableau des valeurs de mort de base

	public LIFFileReader(String fileName) {
		try {
			this.LIFReading("LIF/"+fileName);
		} catch (LIFFileException e) {
			System.out.println("Constructor error");
		}
	}

	public void LIFReading(String fileName) throws LIFFileException {

		try {
			Cell add = null;
			int cpt = -1; //
			int posx = 0;
			int posy = 0;
			InputStream ips = new FileInputStream(fileName);
			InputStreamReader ipsr = new InputStreamReader(ips);
			BufferedReader br = new BufferedReader(ipsr);
			String ligne;

			while ((ligne = br.readLine()) != null) {

				String[] tmp = ligne.split(" ");

				if (tmp[0].equals("#Life")) {

					// on affichera la version du format LIF
					System.out.println(tmp[1]);

				} else if (tmp[0].equals("#D")) {

					// on affichera les commentaires
					for (int i = 1; i < tmp.length; ++i) {
						System.out.print(tmp[i] + " ");
					}
					System.out.println();

				} else if (tmp[0].equals("#N")) {

					System.out.println("Rules : Standard rules of the game");

				} else if (tmp[0].equals("#R")) {

				} else if (tmp[0].equals("#P")) {

					if (tmp.length != 3) {
						throw new LIFFileException(
								"error on the line starting with #P");
					} else {
						try {
							posx = Integer.parseInt(tmp[1]);
							posy = Integer.parseInt(tmp[2]);
						} catch (NumberFormatException e) {
							throw new LIFFileException(
									"error on the line starting with #P");
						} finally {
							cpt = 0;
						}
					}

				} else if (tmp[0].charAt(0) != '.' || tmp[0].charAt(0) != '*') {

					if (tmp.length != 1) {
						throw new LIFFileException(
								"error on the line describing the game");
					} else {
						for (int i = 0; i < tmp[0].length(); ++i) {
							if (tmp[0].charAt(i) == '*') {
								System.out.println("pos (x,y) = (" + (posx + i)
										+ "," + (posy - cpt) + ")");
								add = new Cell(new Position(posx + i, posy
										- cpt));
								this.listOfCells.add(add);
							}
						}
						cpt++;
					}

				}
			}
			br.close();

		} catch (IOException e) {
			System.out.println("Erreur de la lecture de fichier");
		}
		System.out.println("Program done!!");
	}

	@Override
	public String toString() {
		return "LIFFileReader [listOfCells=" + listOfCells.toString()
				+ ", valuesOfLife=" + Arrays.toString(valuesOfLife)
				+ ", valuesOfDeath=" + Arrays.toString(valuesOfDeath) + "]";
	}

}
